package org.comet.auxiliary.client.liaobei.wss;

import cn.liaobei.utils.RequestUtil;
import com.fasterxml.jackson.databind.util.JSONPObject;
import io.netty.channel.ChannelHandlerContext;
import javafx.scene.layout.HBox;
import org.comet.auxiliary.client.liaobei.util.AuPaly;
import org.comet.auxiliary.client.swing.versions.v1.SettingFrame;
import org.comet.auxiliary.common.util.JsonUtils;
import org.comet.auxiliary.common.util.StringUtil;
import sun.util.resources.ga.LocaleNames_ga;

import java.io.IOException;
import java.sql.SQLException;
import java.util.*;

public class MsgHelper  extends cn.liaobei.communication.MsgHelper {
    @Override
    public void ICHMethod(HashMap<String, Object> hashMap, ChannelHandlerContext channelHandlerContext) {

    }
    //发送红包集合
    public static Map<String,Red > redMap = new HashMap<>();
    //领完红包集合
    public static Map<String,Red> redOverMap= new HashMap<>();
    //已中奖红包集合
    public static List<Map<String,Red>> redZjMap = new ArrayList<>();
    public static   Integer kNumber = 0;
    //总需要赔付金额
    public static Double xpfMoney = 0d;
    //总领取金额
    public static Double zlqMoney = 0d;

    @Override
    public void TMMethod(ChannelHandlerContext channelHandlerContext, HashMap<String, Object> hashMap) {

        //判断是否是发送红包消息
        if(hashMap.get("msgtp").equals("15")){

            if(!Objects.isNull(hashMap.get("mstuid"))){
                //收到私聊红包
                if(hashMap.get("mstuid").toString().equals(SettingFrame.userInfo.getUid())){
                    Map<String,Object> msg = (Map<String, Object>) hashMap.get("msg");
                    try {
                        if(SettingFrame.lqslhb.isSelected()){
                            try {

                                Thread.sleep( new Double(Double.parseDouble(SettingFrame.m.getText())).longValue()*1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        String takeStr=RequestUtil.takePacket(SettingFrame.userInfo.getUid(),SettingFrame.userInfo.getUuid(),SettingFrame.userInfo.getTk(),msg.get("tno").toString(),hashMap.get("msuid").toString());
                        Map<String,Object>  map = JsonUtils.getMap(takeStr);
                        if(map.get("r").toString().equals("0")){
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                          String  redStr = RequestUtil.queryPacket(SettingFrame.userInfo.getUid(),SettingFrame.userInfo.getUuid(), SettingFrame.userInfo.getTk(),msg.get("tno").toString()
                                    ,SettingFrame.fbId);
                            Map<String,Object> redData = JsonUtils.getMap(redStr);
                            Map<String,Object> redData1 = (Map<String, Object>) redData.get("data");
                            Map<String,Object> redData2= (Map<String, Object>) redData1.get("hb");
                            //修改数据
//                            udpateData(Double.parseDouble(redData2.get("amt").toString()));
                            System.out.println("领取私聊红包成功！");

                                zlqMoney = zlqMoney+Double.parseDouble(redData2.get("amt").toString());
                                //将领取金额存入reddata
                                SettingFrame.sqliteHelper.executeUpdate("update reddata set lqmoney=lqmoney+"+Double.parseDouble(redData2.get("amt").toString())+"  where userid = "+SettingFrame.userInfo.getUid()+" and groupno="+SettingFrame.fbId );
//                            //遍历中奖红包，获取到总需要赔付金额
//                            for (Map<String, Red> stringRedMap : redZjMap) {
//                                for (Map.Entry<String, Red> stringRedEntry : stringRedMap.entrySet()) {
//                                  xpfMoney = xpfMoney+  stringRedEntry.getValue().getZj();
//                                }
//                            }

                                //计算已领取金额
                                if(zlqMoney<xpfMoney){
                                    SettingFrame.znfbLogText.append("\r\n领取私聊红包成功，金额:"+redData2.get("amt").toString()+",还差"+(xpfMoney-zlqMoney));
                                    SettingFrame.znfbLogText.setCaretPosition(SettingFrame.znfbLogText.getText().length());
                                    AuPaly auPaly = new AuPaly("./error.au");
                                    auPaly.play();
                                }else{
                                    SettingFrame.znfbLogText.append("\r\n所有金额赔付完成");
                                    SettingFrame.znfbLogText.setCaretPosition(SettingFrame.znfbLogText.getText().length());
                                    if(SettingFrame.isPf.getText().equals("开始")) {
                                        if (!SettingFrame.isSendOne) {
                                            try {
                                                Thread.sleep(Long.parseLong(SettingFrame.getJgText()) * 1000);
                                            } catch (InterruptedException e) {
                                                e.printStackTrace();
                                            }
                                            SettingFrame.ksBtn.setText("开始");
                                            SettingFrame.begin();
                                        }
                                    }



                                }



                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    System.out.println("收到私聊红包");
                }
            }
            //发送红包消息
            //收到该工具发出去得包
            if(SettingFrame.userInfo.getUid().equals(hashMap.get("msuid").toString()) && SettingFrame.fbId.equals(hashMap.get("msrid").toString())){
                Map<String,Object> data = (Map<String, Object>) hashMap.get("msg");
                //根据红包id查询红包详情
                String redStr= null;
                try {
                    //勾选领取私聊红包延迟
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    redStr = RequestUtil.queryPacket(SettingFrame.userInfo.getUid(),SettingFrame.userInfo.getUuid(), SettingFrame.userInfo.getTk(),data.get("tno").toString()
                            ,SettingFrame.fbId);
                    System.out.println(redStr);
                    Map<String,Object> redData = JsonUtils.getMap(redStr);
                    Map<String,Object> redData1 = (Map<String, Object>) redData.get("data");
                    Map<String,Object> redData2= (Map<String, Object>) redData1.get("hb");
                    Red red = new Red();
                    red.setMoney(Double.parseDouble(redData2.get("amt").toString()));
                    red.setId(redData2.get("hbid").toString());
                    red.setNumber(Integer.parseInt(redData2.get("cnt").toString()));
                    red.setTitle(redData2.get("msg").toString());
                    redMap.put(redData2.get("tno").toString(),red);
                    redOverMap.put(redData2.get("tno").toString(),red);
                    //将红包金额插入发包流水
                    try {
                        SettingFrame.sqliteHelper.executeUpdate("update userdata set " +
                                "fbls = fbls+"+redData2.get("amt")
                                +",send_page_num=send_page_num+1"
                                +" where userid="+SettingFrame.userInfo.getUid());
                        SettingFrame.sqliteHelper.executeUpdate("update userdata set " +
                                "yk = lq_money-fbls"
                                +" where userid="+SettingFrame.userInfo.getUid());
                        //刷新数据
                        SettingFrame.refreshTopData();
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    //添加定时器
//                    System.out.println(redMap.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
//                red.setMoney();
            }
        }else if(hashMap.get("msgtp").equals("16")){
            for(Map.Entry<String, Red> entry : redMap.entrySet()){
                if(redOverMap.containsKey(entry.getKey())){
                    String   redStr = null;
                    try {
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("用户详情:"+SettingFrame.userInfo.toString());
                        redStr = RequestUtil.queryPacket(SettingFrame.userInfo.getUid(), SettingFrame.userInfo.getUuid(), SettingFrame.userInfo.getTk(),entry.getKey()
                                ,SettingFrame.fbId);
                        System.out.println(redStr);
                        Map<String,Object> redData = JsonUtils.getMap(redStr);
                        Map<String,Object> redData1 = (Map<String, Object>) redData.get("data");
                        Map<String,Object> redData2= (Map<String, Object>) redData1.get("hb");
                        System.out.println("红包详情："+redData2);
                        //取到领包用户
                        List<Map<String,Object>>  redList = (List<Map<String,Object>>)redData2.get("rcvrs");
                        if(Objects.equals(redData2.get("cnt"),redList.size())){
                            String getRedStr = "";
                            Integer zhongjiangNum = 0;
                            String title =redData2.get("msg").toString();
                            for (Map<String, Object> map : redList) {
                                System.out.println(map.get("mny").toString());
                                String  str =   map.get("mny").toString().substring(map.get("mny").toString().length()-1);
                                String mny= map.get("mny").toString();
                                String str1= mny .substring(mny.indexOf(".")+1);

                                if(str1.length()<2||mny.indexOf(".")==-1){
                                    str = "0";
                                }

//                                if(map.get("mny").toString().contains("0.")&&map.get("mny").toString().length()==3){
//                                    str="0";
//                                }
                                getRedStr =getRedStr+ (StringUtil.isBlank(getRedStr) ? "" : "-") +str;
                                //计算中奖个数
                                if(title.contains(str)){
                                    zhongjiangNum++;
                                }
                            }
                            //判断有没有中奖
                            Boolean isLoop= false;

                            if(title.length()==1){
                                String[] strAry=   getRedStr.split("-");
                                for (String s : strAry) {
                                    if(title.contains(s)){
                                        isLoop = true;
                                    }
                                }
                            }else if(title.length()>=1){
                                String[] strAry=   getRedStr.split("-");
                                StringBuilder stringBuilder = new StringBuilder();
                                for (String s : strAry) {
                                    stringBuilder.append(s);
                                }
                                String str2 = removerepeatedchar(stringBuilder.toString());
                                char[] titleAry = title.toCharArray();
                                int num = 0;
                                for (char c : titleAry) {
                                    String s = new Character(c).toString();
                                    if(str2.contains(s)){
                                        num++;
                                    }
                                }
                                if(num==title.length()){
                                    isLoop= true;
                                }
                            }
                            String zhongjiang = "未中奖";

                            String zf = "";
                            Double  sumMoney = 0d;
                            if(isLoop){
                               if( SettingFrame.zltzfb.isSelected()){
                                   SettingFrame.znfbLogText.append("\r\n中雷,停止发包");
                                   SettingFrame.isSend =false;
                                   SettingFrame.znfbLogText.setCaretPosition(SettingFrame.znfbLogText.getText().length());
                               }
                                zhongjiang = "中奖";
                                //计算总返金额
                                System.out.println(redData2.get("amt"));
                                sumMoney = Double.parseDouble(redData2.get("amt").toString())  * Double.parseDouble(SettingFrame.blText.getText());
                                zf = "总返:"+sumMoney;
                                xpfMoney = xpfMoney+sumMoney;


                                //中奖,计算盈亏
                                udpateData(xpfMoney);

                                AuPaly auPaly = new AuPaly("./success.au");
                                auPaly.play();
                            }
                            if(SettingFrame.k.isSelected()){
                                if(kNumber>=Integer.parseInt(SettingFrame.hm.getText())){
                                    String title2= SettingFrame.getTitle2();
                                    SettingFrame.hbbtText.setText(title2);
                                }
                            }

                            //空包换码
                            if(SettingFrame.k.isSelected()){
                                if("未中奖".equals(zhongjiang)){
                                    kNumber++;
                                }
                            }

//                            SettingFrame.zlLogText.append("\r\n\r\n\r\n"+zhongjiang);
//                            SettingFrame.zlLogText.append("\r\n红包标题："+redData2.get("msg").toString());
//                            SettingFrame.zlLogText.append("\r\n红包包数："+redData2.get("cnt").toString());
//                            SettingFrame.zlLogText.append("\r\n尾数："+getRedStr);
                            //将中奖红包加入中奖集合
                            Map<String,Red> map = new HashMap<>();
                            Red red = new Red();
                            red.setId(entry.getKey());
                            red.setIsPw(false);
                            red.setZj(sumMoney);
                            red.setYpMoney(0d);
                            map.put(entry.getKey(),red);
                            redZjMap.add(map);
//                            SettingFrame.zlLogText.append("\r\n\r\n\r\n"+zhongjiang+"     包数:"
//                                    +redData2.get("cnt").toString()
//                                    +"    尾数:"+getRedStr+"     备注:"
//                                    +redData2.get("msg").toString()
//                                    +"     "+zf);
//                            SettingFrame.zlLogText.append("3-7-1-2-7  备注019  返50  中奖");
                            Map<String,Object> tableMap = new HashMap<>();
                            tableMap.put("isZJ",zhongjiang);
                            tableMap.put("title",redData2.get("msg").toString());
                            tableMap.put("pagenum",redData2.get("amt").toString());
                            tableMap.put("ws",getRedStr);
                            tableMap.put("zf",zf);
                            tableMap.put("isRender","false");
                            SettingFrame.tableDate.add(tableMap);
                            SettingFrame.renderTable();

                            redOverMap.remove(entry.getKey());
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private void udpateData(Double lqmoney) {
       List<Map<String,Object>> list =  SettingFrame.getList("userdata");
        Map<String,Object>map = list.get(0);
        lqmoney = lqmoney+  Double.parseDouble(map.get("lq_money").toString());
        Double fbls  = Double.parseDouble(map.get("fbls").toString());
        Double yk = lqmoney-fbls;
        try {
            SettingFrame.sqliteHelper.executeUpdate("update userdata set lq_money="+lqmoney+",yk="+yk+" where userid="+SettingFrame.userInfo.getUid());
            SettingFrame.ykText.setText(yk.toString());
            SettingFrame.fblsText.setText(fbls.toString());
            SettingFrame.lqjeText.setText(lqmoney.toString());

            SettingFrame.sqliteHelper.executeUpdate("update reddata set yk="+lqmoney+"-sendmoney where userid="+SettingFrame.userInfo.getUid()+" and groupno = "+SettingFrame.fbId);






        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


    }

    public static String removerepeatedchar(String s) {
        if (s == null)
            return s;
        StringBuilder sb = new StringBuilder();
        int i = 0, len = s.length();
        while (i < len) {
            char c = s.charAt(i);
            sb.append(c);
            i++;
            while (i < len && s.charAt(i) == c) {
                i++;
            }
        }
        return sb.toString();
    }



    public static void timer1(){

        Timer nTimer = new Timer();

        nTimer.schedule(new TimerTask() {

            @Override

            public void run() {

                System.out.println("----设定要指定任务-----");

            }

        },2000);

    }

}
